#'
#' The Species Area Relationship of a community in a rectangle plot
#' 
#' @param com a community object
#' @param A vector of area of the sample quadrats
#' @param na number of the sample scales
#' @param n number of repeated quadrats for each scales
#'
#' @note
#' A rectangle sampling
#'
#'@examples
#'data(BCI)
#'SAR(BCI)
#'
#'@export
SAR=function(com,A=NULL,na=20,n=100){
  plotdim=plotdim(com)
  
  if(is.null(A)){
    sx=seq(0,plotdim[1],length.out=na)
    sy=seq(0,plotdim[2],length.out=na)
    A=sx*sy
  }else{
    k=plotdim[1]/plotdim[2]
    sy=sqrt(A/(1+k^2))
    sx=k*sy
  }
  
  mean_richness=numeric()
  mean_richness[1]=0
  mean_richness[length(A)]=total_richness(com)
  
  sd_richness=numeric()
  sd_richness[1]=0
  sd_richness[length(A)]=0
  
  for(i in 2:(length(A)-1)){
    fx=runif(n,0+sx[i]/2,plotdim[1]-sx[i]/2)
    fy=runif(n,0+sy[i]/2,plotdim[2]-sy[i]/2)
    jindex=frnn(com,fx,fy,qsize=c(sx[i],sy[i]),type="rectangle",info="index")
    qs=unlist(lapply(jindex,function(x) length(unique(com$species[x]))))
    mean_richness[i]=mean(qs)
    sd_richness[i]=sd(qs)
  }
  
  re=data.frame(area=A,mean_richness,sd_richness)
  return(re)
}